package org.example.y24.m11;

public class NewtonRaphson {
    // 定义函数 f(x) = x^3 + x - 1
    public static double f(double x) {
        return x * x * x + x - 1;
    }

    // 定义函数 f(x) 的导数 f'(x) = 3x^2 + 1
    public static double df(double x) {
        return 3 * x * x + 1;
    }

    // 牛顿迭代法
    public static double newtonRaphson(double x0, double epsilon, int maxIterations) {
        double xk = x0;
        for (int k = 0; k < maxIterations; k++) {
            double fxk = f(xk);
            double dfxk = df(xk);
            double xk1 = xk - fxk / dfxk;

            // 检查停止条件
            if (Math.abs(f(xk1)) < epsilon || Math.abs(xk1 - xk) < epsilon) {
                System.out.println("迭代次数: " + (k + 1));
                return xk1;
            }

            xk = xk1;
        }

        System.out.println("达到最大迭代次数");
        return xk;
    }

    public static void main(String[] args) {
        double initialGuess = -0.7;
        double epsilon = 1e-4;
        int maxIterations = 100;

        double root = newtonRaphson(initialGuess, epsilon, maxIterations);
        System.out.println("近似根: " + root);
    }
}
